
const SMACK_TINYURL_ENABLE = "extensions.swaksmack.tinyurl_enable_boolpref1";
const SMACK_TINYURL_THRESHOLD = "extensions.swaksmack.tinyurl_maxurllength_intpref";

const SS_chatPostRegexStr = "(http:\\/\\/[^\"'\\s>]*\\/?([^\"'\\s>]*)?)";
const SS_chatPostRegEx = new RegExp(SS_chatPostRegexStr, "ig");

var SS_literals_0651 = /(\/|\.|\^|\$|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g;

var SS_literals = /(\/|\.|\^|\$|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g;

var SS_charUIDChoices = "abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWZYZ_";

var SS_defaultSTCInterval = 10000;
var SS_pauseSTCInterval = 60000;

const _jellyfishInfoPMResultRegExStr =  "<a href=\"/shoppers/me/messages\" id=\"alertEnvelope\" title=\"Check Your Messages\" class=\"(noNew)?\"></a>";
//<a href="/shoppers/me/messages" id="alertEnvelope" title="Check Your Messages" class=""></a>
const _jellyfishInfoChatResultRegExStr = "<a href=\"/shoppers/me\" id=\"alertChat\" title=\"Check Your Living Room Chat\" class=\"(noNew)?\"></a>";

var JF_PM_regexp	= new RegExp(_jellyfishInfoPMResultRegExStr, "i");
var JF_LR_regexp	= new RegExp(_jellyfishInfoChatResultRegExStr, "i");
var JF_nicname_regexp = new RegExp("(.*)\\s<span id=\"infoCashBack\">\\$.*<\\/span>");
var JF_CAPS_regexp = new RegExp("[-!\^\$#%@+=_?.:*]*[A-Z]{2,}[-!\^\$#%@+=_?:.*]*\\s*","g");
var JF_CAPSIGNORE_regexp = new RegExp("[-!\^\$#%@+=_?.:*]*","g");

var JF_DebugAlertFired = false;

 
 String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function SS_getStringTableText(key) {
	var jellyfishstrings = document.getElementById("swaksmack-strings");
	return jellyfishstrings.getString(key);
}

function SS_getPreference(pref_name)
{
  var pref_type = SS_prefs.getPrefType(pref_name);
  if (pref_type == SS_prefs.PREF_STRING)
      return SS_prefs.getCharPref(pref_name);
  else if (pref_type == SS_prefs.PREF_INT)
      return SS_prefs.getIntPref(pref_name);
  else if (pref_type == SS_prefs.PREF_BOOL)
      return SS_prefs.getBoolPref(pref_name);
  else  // fallback on error
    return SS_prefs.PREF_INVALID;
}

function swakAppendWordToCharPref(newword,charPref) {
	if (newword == null || charPref == null) return false;
	var words = SS_getPreference(charPref);
	if (words != null) {
		var f = words.indexOf(newword);
		if (f != -1) return false;
	}
	if (words == null || words == '') {
		words = newword;
	}
	else {
		words+=',' + newword;
	}
	ssopts.setCharPref(charPref,words);
	return true;
}

function swakDoesCharPrefContain(word,charPref) {
	if (word == null || charPref == null) return false;
	var words = SS_getPreference(charPref);
	if (words != null) {
		var t = "\\b" + word + "\\b";
		var sre = new RegExp(t,"ig");
		return sre.test(words);
		
	}
	return false;
}

function swakRemoveWordFromCharPref(word,charPref) {
	if (word == null || charPref == null) return false;
	var words = SS_getPreference(charPref);
	if (words == null || words == '') {
		return false;
	}
	//match on word boundary
	var t = "\\b" + word + "\\b";
	var sre = new RegExp(t,"i");
	if (sre.test(words) == true) {
		//word found in prefs, try to remove
		words = words.replace(sre,'');
		words = words.replace(/[,]{2,}/g,',');
		words = words.replace(/[,]+$|^[,]+|/g,'')
		ssopts.setCharPref(charPref,words);
		return true;
	}
	return false;
}

function swakESTGetDayOfYear() {
	var singleDay=1000*60*60*24;
	var today = new Date();
	var dst = swakIsDST(today);
//	alert('is dst ' + dst);
	var eoffset = -5;
	if (dst == true) {
		eoffset = -4;
	}
	var local = today.getTime();
	var localOffset = today.getTimezoneOffset() * 60000;
	var utc = local + localOffset;
//	alert('eoffset ' + eoffset);
	var temp = utc + (3600000*eoffset);
	var etzdate = new Date(temp);
//	alert('etzdate ' + etzdate);
	return swakGetDayOfYear(etzdate);
	
	
	/*
	var local = today.getTime();
	var localOffset = d.getTimezoneOffset() * 60000;
	var utc = local + localOffset;
	var ESTOffset = -4;
	
	var yearStart=new Date(today.getFullYear(), 0, 1);
	
	var doy = Math.ceil((today.getTime() - yearStart.getTime()) / singleDay);
	return doy;
	*/
}

function swakGetDayOfYear(theDate) {
//	alert('swakGetDayOfYear entry ' + theDate);
	if (theDate == null) {
		theDate = new Date();
	}
	var singleDay=1000*60*60*24;
	var yearStart=new Date(theDate.getFullYear(), 0, 1);
	
	var doy = Math.ceil((theDate.getTime() - yearStart.getTime()) / singleDay);
	return doy;
}

function swakDSTdatesUS( yr )
{
	if ( yr<1987 ) return; // Outside range
	
	// Work out last possible on/off date
	var don = (yr<2007)? 38 : 14;
	var dof = (yr<2007)? 31 : 38;
	
	// Create initial on/off date objects
	var DSTon = new Date(yr, 2, don, 2);
	var DSToff = new Date(yr, 9, dof, 2);
	
	// Adjust to Sunday before last possible date (adjustment may be 0)
	DSTon.setDate( DSTon.getDate() - DSTon.getDay() );
	DSToff.setDate( DSToff.getDate() - DSToff.getDay() );
	
	return [DSTon, DSToff];
}

function swakIsDST(theDate) {
	if (theDate == null ) return false;
	var year = theDate.getFullYear();
//	alert('year ' + year);
	var dst = swakDSTdatesUS(year);
 	//alert(dst);
 	//alert(dst[0] + " DST dates  " + dst[1]);
 	
 	if (theDate > dst[0] && theDate < dst[1]) {
 		return true;
 	}
 	else {
 		return false;
 	}
}

function swakGetNumOfCaps(text) {
	//alert('count all caps ' + text);
	if (text == null || text == '') return 0;
	//var re = new RegExp("([A-Z]){2,}\\b","g");
	//alert('caps re ' + re);
	var matches = text.match(JF_CAPS_regexp);
	//alert('matches ' + matches);
	if (matches != null && (matches.length>1 || text.length > 10)) {
		var count = 0;
		for (var i=0;i<matches.length;i++) {
			var w = matches[i];
			count+=w.length;
		}
		//alert('count ' + count);
		return count;
	}
	return 0;

}

function swakReplaceAllCaps(text) {
	if (text == null || text == '') return null;
	var ft = text.replace(JF_CAPSIGNORE_regexp,'');
	var len = ft.length;
	var caps = swakGetNumOfCaps(ft);
	var tpref = SS_getPreference(SMACK_CAPSTHESHOLD);
	if (tpref > 100) return;
	if (tpref < 0) tpref = 0;
	var threshold = tpref/100;
	var ratio = caps/len;
	//alert(len + " len, cap ratio " + ratio);
	if (ratio >= threshold) {
		
		var lower = text.toLowerCase();
		//alert('convert to lower ' + lower);
		return lower;
	}
	return null;
	
}

function swakGetProduct() {
	var keyword = '';
	var product = swaksmack.SmackShopDoc.getElementById('productNameAnchor');
	if (product == null) {
		return null;
	}
	
 	keyword = product.textContent;
	var crap = keyword.indexOf('-NYD');
	if (crap != -1) {
		keyword = keyword.substring(0,crap);
	}
	return keyword;
}

function SS_getCharUID(generateNew) {
	if (generateNew == null) generateNew = false;
	if (SS_CHARUID == null || generateNew) {
		var temp = '';
		var size_of_uid = 13;
		for (var i=0; i<size_of_uid; i++) {
  		var rnd = Math.floor(Math.random() * SS_charUIDChoices.length);
  		temp += SS_charUIDChoices.substring(rnd,rnd+1);
		}
		SS_CHARUID = temp;

	} 
	return SS_CHARUID;
}


function SS_getChatPostUrlText(postText) {
	var matches	= null;
	var results = new Array();
	var numMatch = 0;
	while ((matches = SS_chatPostRegEx.exec(postText)) != null) {
		//check if url end with :.!, and remove
		//alert('matches[1]' + matches[1]);
 		var newurl = matches[1].replace(/[\.!,;:]$/i,'');
 		results[numMatch++] = newurl;
	}
	
 	return results;
}

//converts regex literals characters in the parameter 
function SS_escapeRegExLiterals(plaintext) {
	if (plaintext == null) return null;
	var converted = plaintext.replace(SS_literals,"\\$1");
	return converted
}

function SS_getRandomNumber(maxNum) {
	if (maxNum == null) maxNum = 100;
	var randomGuess = Math.ceil(Math.random()*maxNum);
	return randomGuess;
}

function SS_getSmackShoppingWindow() {
	var num = gBrowser.browsers.length;
	for (var i = 0; i < num; i++) {
	  var b = gBrowser.getBrowserAtIndex(i);
	  try {
	  	var doc = b.contentWindow.document;
	  	var sa = isSmackShopArea(doc);
	  	if (sa == true) {
	  		//alert('browser doc ' + b.contentWindow.document);
	  		return b.contentWindow;
	  	}
	    //dump(b.currentURI.spec); // dump URLs of all open tabs to console
	  } catch(e) {
	    //Components.utils.reportError(e);
	  }
	}
	return null;
}

function openOptions() {
	//alert('openOptions');
	    window.openDialog(
        "chrome://swaksmack/content/options.xul", 
        "options",
        "chrome, dialog, centerscreen");
}

function Swak_openTV1(dblclick) {
	if(dblclick == null) dblclick = false;
	if (dblclick) {
	if (swaksmack.SS_SBM !=null) {
		swaksmack.SS_SBM.toggleSaleInfo();
	}

	}
	else { 
		Swak_openUrl("http://www.jellyfish.com/smacktv/channel/1");
	}
}

function Swak_openPM() {
	//alert('open PM');
	Swak_openUrl("http://www.jellyfish.com/shoppers/me/messages#", true);
	//openAndReuseOneTabPerURL("http://www.jellyfish.com/shoppers/me/messages");
	/*
	var index = Swak_getTabIndex("http://www.jellyfish.com/shoppers/me/messages");
	if (index == -1)
		gBrowser.selectedTab = gBrowser.addTab("http://www.jellyfish.com/shoppers/me/messages");
	else
		*/	
	//window.open("http://www.jellyfish.com/shoppers/me/messages");
}

function Swak_openUrl(theurl,reload, referrer) {
	if (theurl == null) return;
	if (reload == null) reload = false;
	var index = Swak_getTabIndex(theurl);
	if (index != -1) {
		//var currentTab = gBrowser.getBrowserAtIndex(index);
		gBrowser.mTabContainer.selectedIndex = index;
	}
	else {
		if (referrer != null && referrer != '') {
			try {
				var iosvc = Components.classes["@mozilla.org/network/io-service;1"]
	                      .getService(Components.interfaces.nsIIOService);
				var referrerURI = iosvc.newURI(referrer, null, null); 
				gBrowser.selectedTab = gBrowser.addTab(theurl,referrerURI,null, null, null, false);
			}
			catch (x) {}
			}
	else {
		gBrowser.selectedTab = gBrowser.addTab(theurl);
	}

		
///		gBrowser.selectedTab = gBrowser.addTab(theurl);
		return;
	}
	if (reload == true) {
		gBrowser.reload();
	}
}

function Swak_openLR() {
	Swak_openUrl("http://www.jellyfish.com/shoppers/me");
}

function Swak_getTabIndex(uriName) {
	if (uriName == null) return -1;
	var num = gBrowser.browsers.length;
	var index = -1;
	for (var i = 0; i < num; i++) {
	  var b = gBrowser.getBrowserAtIndex(i);
	  try {
	  	if (b.currentURI.spec == uriName) {
	  		index = i;
	  		break;
	  	}
	    //dump(b.currentURI.spec); // dump URLs of all open tabs to console
	  } catch(e) {
	    //Components.utils.reportError(e);
	  }
	}
	return index;
}

function SS_testAudioFile() {
	var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
  playAudioAlert(soundFile);
}

function JellyFishPMChecker() {
}

JellyFishPMChecker.prototype.id = null;
JellyFishPMChecker.prototype.pollInterval = 120000;
JellyFishPMChecker.prototype.minPollInterval = 90000;

JellyFishPMChecker.prototype.previousPM = false;
JellyFishPMChecker.prototype.previousChat = false;


JellyFishPMChecker.prototype.setInterval = function(interval) {
	this.pollInterval = interval;
}

JellyFishPMChecker.prototype.stopCheck = function() {
	//alert('stop PM check ' + this.id);
	if (this.id != null) {
		
		clearInterval(this.id);
		this.id = null;
	}
	this.pollInterval = null;
}

JellyFishPMChecker.prototype.checkPM = function() {
	this.pollInfo();
}

JellyFishPMChecker.prototype.pollInfo = function() {
	this.minPollInterval = SS_getPreference(SMACK_MINPMPOLLINTERVAL);
	var pmpoll = SS_getPreference(SMACK_CHECKPMCHAT);
	if (pmpoll == false) {
		return;
	}
	var lasttime = swaksmack.lastPMCheckTime;
	var ctime = new Date().getTime();
	var pmcheckokay = false;
	if (lasttime != null) {
		var diff = ctime -lasttime;
		if (diff >= this.minPollInterval) {
			pmcheckokay = true;
		}
	}
	
	if (lasttime == null || pmcheckokay == true) {
	
		swaksmack.lastPMCheckTime = ctime;
	
		var info = new JellyFishInfoRequest('');
		 			var jfInfoCB = {
				ondone : function(handle){
						//alert(handle.infoChatResult+ ' JF PM check done ' + handle.infoPMResult);
						onPMUpdate(this.previousPM, handle.infoPMResult, this.previousChat, handle.infoChatResult);
						this.previousPM = handle.infoPMResult;
						this.previousChat = handle.infoChatResult;

				},
				
				onerror : function(handle){
				}
			}
	 	info.execute(jfInfoCB);
	}
	else {
		//used to test bypassing of pm check
		//alert('pm throttle');
	}
	
	if (this.pollInterval < this.minPollInterval) {
		alert('PM Checking Not Working.  Please Notify Mindstorm of this Error: PM Check Error Time1');
		ssopts.setBoolPref(SMACK_CHECKPMCHAT,false);
		return;
	}
 	this.id = setInterval(this.pollInfo,this.pollInterval);
}


function JellyFishInfoRequest(url1){

	this.sourceURL = url1;
	
	//if true, new PM
	this.infoPMResult = false;
	
	//if true, new LR chat
	this.infoChatResult = false;
	
	//tinyurl httprequest
	this.request = null;
	
		//execute the tiny url request
	this.execute = function(callback){
		
		// No need to shrink
		if(this.infoResult != null){
			return;
		}
		
		if (swaksmack.PMChecker == null) {
			//alert('PMChecker null--no query');
			return;
		}
		
		// check if there is an outstanding request
		if(this.request != null){
			this.request.abort();
		}
		
		// Setup Request	
		this.request	= new XMLHttpRequest();
		this.request.open("GET", "http://www.jellyfish.com/smacktv/channel/1", true); //(default)true:async - false: sync
		this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.request.setRequestHeader("User-Agent", navigator.userAgent);
		//this.request.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

		
		//url substitutions
		var url = this.sourceURL;
   	//url = url.replace(/\+/g, "%2B").replace(/&/g, '%26').replace(/\?/g, '%3F').replace(/=/g, '%3D');       	
		
		//store reference to stuff
		var handle = this;

		
		// Handle request
		this.request.onload = {
			handleEvent : function(e){
				
				// If already aborted
				if(handle.request == null){
					return;
				}
				
				//get html from response and look for tunyurl
				var html = handle.request.responseText;
				handle.infoResult = null;
				
				//var regexp	= new RegExp(_jellyfishInfoPMResultRegExStr, "i");
				var jfresult	= JF_PM_regexp.exec(html);
				//alert('jfresult pm result ' + jfresult);
				//swaksmack.alertManager.swakAlert(SMACK_ALERT_GURUGUESS, true, 5000, true);
				if(jfresult != null && jfresult.length > 0){
					var pmnonewmatch = jfresult[1];
					if (jfresult[1]!= null) {
						handle.infoPMResult = false;
					}
					else {
							//alert('new PM?');
						handle.infoPMResult = true;
					}  				
				}
				
				//var regexp2	= new RegExp(_jellyfishInfoChatResultRegExStr, "i");
				jfresult	= JF_LR_regexp.exec(html);
			//	alert('jfchatresult ' + jfresult);
				if(jfresult != null && jfresult.length > 0){
					var pmnonewmatch = jfresult[1];
					if (jfresult[1] != null) {
						handle.infoChatResult = false;
					}
					else {
						handle.infoChatResult = true;
					}  				
				}
				
				callback.ondone(handle);
				
				/**
				// callback to onerror or ondone
				if(handle.infoResult == null || handle.infoResult==""){
					callback.onerror(handle);
				}
				else{
					//should just be sending back the tunyurl as a string
					callback.ondone(handle);
				}
				*/
			}
		};
		
		// check if the xmlhttprequest had an error--if so, callback to error
		this.request.onerror = {
			handleEvent : function(e){
				callback.onerror(handle);
			}
		}
       	      	
    //send request
    this.request.send("url="+ url);
	}
}

function FileChooser(title,am) {
	this.title = title;
	this.audioManager = am;
//	this.id = id;
}

FileChooser.prototype.open = function() {
  try {
	//  const cc=Components.classes;
	//  const ci=Components.interfaces;
	  var filePicker = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
	  
	 // filePicker.init(window,title,Components.interfaces.nsIFilePicker.modeOpen);
	  filePicker.init(window,this.title,Components.interfaces.nsIFilePicker.modeOpen);
	  filePicker.appendFilter("wav file","*.wav");
	  filePicker.filterIndex = 0;
	  const ret=filePicker.show();
	  if (ret==Components.interfaces.nsIFilePicker.returnOK || ret==Components.interfaces.nsIFilePicker.returnReplace) {	   
	   var result = this.playAudio(filePicker.fileURL.spec);
	   if (result) {
	   	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch).getBranch("");
	   	prefs.setCharPref(SMACK_AUDIOSOUND_OUTWIT,filePicker.fileURL.spec);
	   }
	  }
	} catch(ex) {
  	alert('Error choosing file ' + ex);
	}
}

FileChooser.prototype.playAudio = function(audioFile) {
	if (audioFile == null) return;
	try {
		return this.audioManager.playAudioAlert(audioFile);
	} 
	catch(ex) {
		alert("Playing sound failed..." + ex);
		return false;
	}
}

const SMACK_STATE_UNKNOWN = "STATE_UNKNOWN";
const SMACK_STATE_PREVIEW = "STATE_PREVIEW";
const SMACK_STATE_GURUGUESSENTER = "STATE_GURUGUESSENTER";
const SMACK_STATE_GURUGUESSMADE = "STATE_GURUGUESSMADE";
const SMACK_STATE_GURUGUESSMISSED = "STATE_GURUGUESSMISSED";
const SMACK_STATE_GURUGUESSWHEELSPIN = "STATE_GURUGUESSWHEELSPIN";
const SMACK_STATE_GURUGUESSWHEELSPINSTOPPED = "STATE_GURUGUESSWHEELSPINSTOPPED";
const SMACK_STATE_OUTWITOPTIN = "STATE_OUTWITOPTIN";
const SMACK_STATE_OUTWITOPTINENTERED = "STATE_OUTWITOPTINENTERED";
const SMACK_STATE_OUTWITSELECTCONTESTANT = "STATE_OUTWITSELECTCONTESTANT";
const SMACK_STATE_OUTWITCONTESTANTSELECTED = "STATE_OUTWITCONTESTANTSELECTED";
const SMACK_STATE_OUTWITVOTE = "STATE_OUTWITVOTE";
const SMACK_STATE_OUTWIT_VOTED = "STATE_OUTWIT_VOTED";
const SMACK_STATE_OUTWITMISSED = "STATE_OUTWITMISSED";
const SMACK_STATE_OUTWITRESULT = "STATE_OUTWITRESULT";
const SMACK_STATE_GURUGUESSSOLD = "STATE_GURUGUESSSOLD";
const SMACK_STATE_NONGURUDEAL = "STATE_DEAL";
const SMACK_STATE_NONGURUDEALSOLD = "STATE_DEALSOLD";
const SMACK_STATE_SMACKPOT_BETOPEN = "STATE_SMACKPOTBETOPEN";
const SMACK_STATE_SMACKPOT_BETMADE = "STATE_SMACKPOTBETMADE";
const SMACK_STATE_SMACKPOT_BETCLOSED = "STATE_SMACKPOTBETCLOSED";
const SMACK_STATE_SMACKPOT_RESULTS = "STATE_SMACKPOTRESULT";

function JellyFish() {
}

//JellyFish.prototype.contWindow = null;
JellyFish.prototype.chatPaused = false;
JellyFish.prototype.outwitRandomContestantPaused = false;
JellyFish.prototype.chatSpeed = 10000;
JellyFish.prototype.nickname = '';

JellyFish.prototype.getNickName = function() {
	if (this.nickname == '') {
		var inn = content.document.getElementById('infoNickName');
		if (inn != null && inn != 'undefined') {
			//var re = new RegExp("(.*)\\s<span id=\"infoCashBack\">\\$.*<\\/span>");
			var matches = JF_nicname_regexp.exec(inn.innerHTML);
			if (matches != null && matches.length>0) {
				this.nickname = matches[1];
			}
			//gBrowser.contentWindow.wrappedJSObject.window.nickname;  //doesn't work for LR
		}
	}
	return this.nickname;
}

JellyFish.prototype.toggleChat = function() {
	var cs = gBrowser.contentWindow.wrappedJSObject.s;
	//if (cs == null || cs == undefined) return false;
	//alert('this.chatPaused ' + this.chatPaused);
	if (this.chatPaused == false) {
		cs.stop();
		cs.interval = SS_pauseSTCInterval;
		cs.start();
		//cs.stop();
		this.chatPaused = true;
		//alert('chat paused');
	}
	else {
		//cs.start();
		cs.stop();
		cs.interval = SS_defaultSTCInterval;
		cs.start();
		this.chatPaused = false;
		//alert('chat resumed');
	}
	return this.chatPaused;
	
}

JellyFish.prototype.isChatPaused = function() {
	return this.chatPaused;
}


JellyFish.prototype.setChatSpeed = function(speed) {
	
	if (speed == null) return;
	if (isNaN(speed))return;
	var newspeed = speed * 1000;
	//alert(this.chatSpeed + ' (this.cs) setChatSpeed newspeed ' + newspeed);
	if (newspeed == this.chatSpeed) return;
	if (newspeed < 1000) return;
	if (newspeed > 60000) return;
	
	//var newspeed = speed * 1000;
	var mylo = gBrowser.contentWindow.wrappedJSObject.s;
	if (mylo == null) {
		//alert('liveobject null');
		return;
	}
	this.chatSpeed = newspeed;
	
	mylo.stop();
	mylo.interval = newspeed;
	mylo.start();
	// alert('chat speed changed to ' + this.chatSpeed);
}

JellyFish.prototype.getChatSpeed = function() {
	return this.chatSpeed;
}

JellyFish.prototype.outwitRandomContestantToggle = function() {
	var mylo = gBrowser.contentWindow.wrappedJSObject.liveObject;
	if (mylo == null) {
		//alert('liveobject null');
		return;
	}
	
	if (mylo instanceof gBrowser.contentWindow.wrappedJSObject.CompletedOutwitRegistration) {
		alert(mylo.cylonTimer + ' cylon, timerSpeed ' + mylo.timerSpeed);
		//mylo.timerSpeed = 10000;
//		clearInterval(mylo.cylonTimer);
		//mylo.enoughToPlay = false;
		mylo.contestantSet = true;
		mylo.draw();
		var mylot = gBrowser.contentWindow.wrappedJSObject.liveObjectTimer;
		if (mylot != null) {
		mylot.decrement = 5;
		mylot.speed = 5000;
		mylot.updateTimer();
		alert('timer updated');
		}
		alert('end cont stop');
	}
	else {
		alert('liveobject not CompletedOutwitRegistration');
		return;
	}
	
	return this.outwitRandomContestantPaused;
	
}

JellyFish.prototype.isOutwitRandomContestantPaused = function() {
	return this.outwitRandomContestantPaused;
}


JellyFish.prototype.getGuruGuessStatusRnD = function() {
	var sc = new XPCNativeWrapper(gBrowser.contentWindow, "s");//SmackTVController(1);
	alert('gBrowser.contentWindow ' + gBrowser.contentWindow);
	var unsafeTarget = new XPCNativeWrapper(gBrowser.contentWindow, "s").s;
	alert('util unsafeTarget ' + unsafeTarget);
	var sco = new XPCNativeWrapper(gBrowser, 'contentWindow').contentWindow;
	var sco1 = new XPCNativeWrapper(sco, 's').s;
	alert('sco ' + sco);
	alert('sco1 ' + sco1);
	var sc1 = new XPCNativeWrapper(gBrowser.contentWindow.s, "guru_guessing_state").guru_guessing_state;//SmackTVController(1);
	alert('sc1 ' + sc1);
	var sc1a = new XPCNativeWrapper(gBrowser.contentWindow, 's', 'guru_guessing_state').guru_guessing_state;
	alert('sc1a ' + sc1a);
	//var mys = new sc.SmackTVController(1);
	var scobject = new XPCNativeWrapper(gBrowser.contentWindow.s, "guru_guessing_state");
	alert('scobject ' + scobject);
	alert('scobject ggs ' + scobject.guru_guessing_state);
	var ggsWrapper = new XPCNativeWrapper(sc.s, "guru_guessing_state");

	
	alert('ggsWrapper ' + ggsWrapper);
}

JellyFish.prototype.getGuruGuessState = function() {
	try {
		var mys = swaksmack.smackShopContentWindow.wrappedJSObject.s;
		var ggs = mys.guru_guessing_state;
		return ggs;
	}
	catch(x) {
		if (JF_DebugAlertFired == false) {
			//alert('guru guess state query failure: ' + x);
			JF_DebugAlertFired = true;
		}
		//swaksmack.alertManager.swakAlert(SMACK_ALERT_CUSTOM, true, 10000, true);
	}
	return null;
}

JellyFish.prototype.getTypeIdentifier = function() {
	try {
		var mylo = swaksmack.smackShopContentWindow.wrappedJSObject.liveObject;
		var ti = mylo.typeIdentifier;
		return ti;
	}
	catch(x){
		if (JF_DebugAlertFired == false) {
			//alert(swaksmack.smackShopContentWindow + ', smackShopContentWindow, type identifier query failure: ' + x);
			JF_DebugAlertFired = true;
		}
		//swaksmack.alertManager.swakAlert(SMACK_ALERT_CUSTOM, true, 10000, true);
		}
	return null;
}

JellyFish.prototype.isContestantSet = function() {
	try {
		var mylo = swaksmack.smackShopContentWindow.wrappedJSObject.liveObject;
		var cs = mylo.contestantSet;
		return cs;
	}
	catch(x){}
	return null;
}

JellyFish.prototype.isUserInOutwit = function() {
	try {
		var mylo = swaksmack.smackShopContentWindow.wrappedJSObject.liveObject;
		var cs = mylo.userIsIn;
		return cs;
	}
	catch(x){}
	return true;
}

JellyFish.prototype.isAlreadyClicked = function() {
	var mylo = swaksmack.smackShopContentWindow.wrappedJSObject.liveObject;
	var cs = mylo.alreadyClicked;
	return cs;
}

JellyFish.prototype.getSmackPotTypeIdentifier = function() {
	try {
		var mysp = swaksmack.smackShopContentWindow.wrappedJSObject.smackPotObject;
		var ti = mysp.typeIdentifier;
		return ti;
	}
	catch(x){
		if (JF_DebugAlertFired == false) {
			//alert('smack pot query failure: ' + x);
			JF_DebugAlertFired = true;
		}
		//swaksmack.alertManager.swakAlert(SMACK_ALERT_CUSTOM, true, 10000, true);
	}
	return '';
}

JellyFish.prototype.getSmackPotEditBet = function() {
	try {
		var mysp = swaksmack.smackShopContentWindow.wrappedJSObject.smackPotObject;
		var ti = mysp.editableWagers;
		return ti;
	}
	catch(x){}
	return '';
}

JellyFish.prototype.getSmackPotCoinsWon = function() {
	try {
		var mysp = swaksmack.smackShopContentWindow.wrappedJSObject.smackPotObject;
		var ti = mysp.playersCoinsWon;
		return ti;
	}
	catch(x){}
	return 0;
}

JellyFish.prototype.isUnknownState = function() {
	var flag = false;
	if (swaksmack.smackShopContentWindow == null) {
		return true;
	}
	var typeid = this.getTypeIdentifier();
	if (typeid == null || typeid == 'undefined') {
		 return true;
	}
	return flag;
}

JellyFish.prototype.getState = function() {
	if (swaksmack.smackShopContentWindow == null) {
		if (isSmackShopArea(content.document) == true) {
				//alert('runtime reinitialization of smackShopContentWindow');
				swaksmack.smackShopContentWindow = gBrowser.contentWindow;
		}
		else {
			return SMACK_STATE_UNKNOWN;
		}
	}
	
	var typeid = this.getTypeIdentifier();
	var ggs = this.getGuruGuessState();
	var smackpotid = this.getSmackPotTypeIdentifier();
	//alert('getState called...typeid ' + typeid);
	if (typeid == null || typeid == 'undefined') {
		//alert('typeid null or undefined ' + typeid);
		 return SMACK_STATE_UNKNOWN;
	}
	
	if (typeid =='LiveDeal') {
		if (smackpotid == 'OpenBetting') {
			var editbet = this.getSmackPotEditBet();
			if (editbet == false) {
				return SMACK_STATE_SMACKPOT_BETMADE;
			}
			else if(editbet == true) {
				return SMACK_STATE_SMACKPOT_BETOPEN;
			}
			else {
				//alert('editbet value ' + editbet);
				return SMACK_STATE_SMACKPOT_BETOPEN;
			}
		}
		else if (smackpotid == 'ClosedBetting') {
			return SMACK_STATE_SMACKPOT_BETCLOSED;
		}
		//end smackpot stuff
		if (ggs == 'NoGuessing') {
			return SMACK_STATE_NONGURUDEAL;
		}
		else if (ggs == 'MakeGuess') {
			return SMACK_STATE_GURUGUESSENTER;
		}
		else if (ggs == 'GuessClosed') {
			return SMACK_STATE_GURUGUESSMADE;
		}
		else if (ggs == 'NoGuessClosed') {
			return SMACK_STATE_GURUGUESSMISSED;
		}
	}
	else if (typeid == 'LiveOutwit') {
		try {
			var voted = this.isAlreadyClicked();
			if (voted) {
				return SMACK_STATE_OUTWIT_VOTED;
			}
			else if (this.isUserInOutwit() == false) {
				return SMACK_STATE_OUTWITMISSED;
			}
			else {
				return SMACK_STATE_OUTWITVOTE;
			}
		}
		catch (x) {
			//alert(x);
		}
		
		//handle the case wehre user votes and then refreshes/restarts browser
		var ansdiv = swaksmack.SmackShopDoc.getElementById(SMACK_OUTWITANSWERDIV);
		if (ansdiv == null) {
			return SMACK_STATE_OUTWIT_VOTED;
		}
		
		return SMACK_STATE_OUTWITVOTE;
	}
	else if (typeid == 'SoldOutDeal') {
		
		if (smackpotid == 'BettingResults') {
			return SMACK_STATE_SMACKPOT_RESULTS;
		}
		
		if (ggs == 'NoGuessing') {
			return SMACK_STATE_GURUGUESSSOLD;
		}
		else if (ggs == 'GuruWinners') {
			return SMACK_STATE_GURUGUESSSOLD;
		}
	}
	else if (typeid == 'CompletedOutwit') {
		return SMACK_STATE_OUTWITRESULT;
	}
	else if (typeid == 'LiveOutwitRegistration') {
		try {
			//this.contWindow
			var owcapdiv = swaksmack.SmackShopDoc.getElementById('captchaBox');
			//var owcapdiv = this.contWindow.document.getElementById('captchaBox');
				if (owcapdiv == null || owcapdiv.style.display == "none") {
					return SMACK_STATE_OUTWITOPTINENTERED;
				}
			}
		catch(x){
			//alert(x);
		}
		return SMACK_STATE_OUTWITOPTIN;
	}
	else if (typeid == 'CompletedOutwitRegistration') {
		if (this.isContestantSet()) {
			try {
				return SMACK_STATE_OUTWITCONTESTANTSELECTED;
			}
			catch(x){}
		}
		return SMACK_STATE_OUTWITSELECTCONTESTANT;
	}
	else if (typeid == 'LiveSmackWheel') {
		return SMACK_STATE_GURUGUESSWHEELSPIN;
	}
	else if (typeid == 'StoppedSmackWheel') {
		return SMACK_STATE_GURUGUESSWHEELSPINSTOPPED;
	}	
	else if (typeid == 'ShowPreview') {
		return SMACK_STATE_PREVIEW;
	}			
	else {
		return SMACK_STATE_UNKNOWN;
	}
}

JellyFish.prototype.isGuruWinner = function() {
	try {
		var gwb = getElementsByClassName('guruWinnerBlock',swaksmack.smackShopContentWindow.document);
		if (gwb != null && gwb[0] != null) {
			return true;
		}
	}
	catch(x) {
		return false;
	}
	return false;
}

JellyFish.prototype.isContestWinner = function() {
	try {
		var cwb = getElementsByClassName('contestantWinnerBlock',swaksmack.smackShopContentWindow.document);
		if (cwb != null && cwb[0] != null) {
			return true;
		}
	}
	catch(x) {
		return false;
	}
	return false;
}

JellyFish.prototype.getSmackMostRecentCommentId = function() {
	try {
		var mys = swaksmack.smackShopContentWindow.wrappedJSObject.s;
		return mys.most_recent_comment_id;
	}
	catch(x) {
	}
	return null;
}

JellyFish.prototype.getSmackChatMonitor = function() {
	try {
		var mycm = swaksmack.smackShopContentWindow.wrappedJSObject.chatMonitor;
		return mycm;
	}
	catch(x) {
	}
	return null;
}

JellyFish.prototype.getChatMonitor2 = function(contWindow) {
	if (contWindow == null) return null;
	try {
		var mycm = contWindow.wrappedJSObject.chatMonitor;
		return mycm;
	}
	catch(x) {
	}
	return null;
}

JellyFish.prototype.getFirstChatId = function(contWindow) {
	if (contWindow == null) return null;
	try {
		var mycm = contWindow.wrappedJSObject.chatMonitor;
		return mycm[0];
	}
	catch(x) {
	}
	return null;
}

JellyFish.prototype.getLastChatId = function(contWindow) {
	if (contWindow == null) return null;
	try {
		var mycm = contWindow.wrappedJSObject.chatMonitor;
		return mycm[mycm.length-1];
	}
	catch(x) {
	}
	return null;
}

JellyFish.prototype.getWheelContestant = function() {
	try {
		var mylo = swaksmack.smackShopContentWindow.wrappedJSObject.liveObject;
		var contestant = mylo.contestant.nickname;
		return contestant;
	}
	catch (x) {}
	return '';
}

JellyFish.prototype.getRetailPrice = function() {
	try {
		var mylo = swaksmack.smackShopContentWindow.wrappedJSObject.liveObject;
		var price = mylo.offering.price;
		return price;
	}
	catch(x){
		if (JF_DebugAlertFired == false) {
			//alert(swaksmack.smackShopContentWindow + ', smackShopContentWindow, type identifier query failure: ' + x);
			JF_DebugAlertFired = true;
		}
		//swaksmack.alertManager.swakAlert(SMACK_ALERT_CUSTOM, true, 10000, true);
		}
	return null;
}

JellyFish.prototype.getDiscount = function() {
	try {
		var mylo = swaksmack.smackShopContentWindow.wrappedJSObject.liveObject;
		var deals = mylo.bestDeals;
		//alert('getDiscount deals[0]  : '+ deals[0].discount);
		//var wdeal = swaksmack.smackShopContentWindow.wrappedJSObject.mylo.bestDeals;
		var discount = deals[0].discount;
		return discount;
	}
	catch(x){
		if (JF_DebugAlertFired == false) {
			//alert(swaksmack.smackShopContentWindow + ', smackShopContentWindow, type identifier query failure: ' + x);
			//JF_DebugAlertFired = true;
		}
		//swaksmack.alertManager.swakAlert(SMACK_ALERT_CUSTOM, true, 10000, true);
		}
	return null;
}

JellyFish.prototype.getSalePrice = function(retail, percentDiscount) {
	if (retail == null || percentDiscount == null) return null;
	try {
		percentDiscount = percentDiscount/100;
		var dp = retail - (retail*percentDiscount);
		var price = swakMoneyFormat(dp);
		return price;
	}
	catch (x) {
		return null;
	}
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }